/**
 * 事件路由
 * 处理事件的 CRUD 操作、列表查询、克隆等功能
 */

import { FastifyPluginAsync } from 'fastify'
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'
import {
    CreateEventSchema,
    CreateEventResponseSchema,
    UpdateEventSchema,
    UpdateEventResponseSchema,
    GetEventResponseSchema,
    DeleteEventResponseSchema,
    EventListQuerySchema,
    EventListResponseSchema,
    CloneEventSchema,
    CloneEventResponseSchema,
    InitializeEventInstancesSchema,
    InitializeEventInstancesResponseSchema
} from '../validators/event.schema'
import {
    createEvent,
    getEventDetail,
    updateEvent,
    deleteEvent,
    initializeEventInstances
} from '../services/event.service'
import type { CreateEventDTO, UpdateEventDTO } from '@services/common/types'

const eventRoutes: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
    const server = fastify.withTypeProvider<TypeBoxTypeProvider>()

    /**
     * 创建事件
     * POST /api/events
     */
    server.post(
        '/api/events',
        {
            schema: {
                description: '创建新事件（支持单次和重复事件）',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                body: CreateEventSchema,
                response: {
                    201: CreateEventResponseSchema
                }
            },
            preHandler: [server.authenticate, server.requireAdmin]
        },
        async (request, reply) => {
            const body = request.body
            const creatorId = request.user!.userId

            // 转换 DTO
            const dto: CreateEventDTO = {
                organizationId: body.organizationId!,
                title: body.title!,
                description: body.description,
                startAt: new Date(body.startAt!),
                endAt: new Date(body.endAt!),
                settings: body.settings as any,
                eventCombinationId: body.eventCombinationId
            }

            const result = await createEvent(dto, creatorId)

            if (!result.success) {
                throw new Error(result.message || '创建事件失败')
            }

            // 转换 Date 为 ISO string
            const transformedData = {
                ...result.data!,
                startAt: result.data!.startAt.toISOString(),
                endAt: result.data!.endAt.toISOString(),
                settings: result.data!.settings as any
            }

            return reply.status(201).send({
                success: true,
                data: transformedData as any
            })
        }
    )

    /**
     * 获取事件详情
     * GET /api/events/:id
     */
    server.get(
        '/api/events/:id',
        {
            schema: {
                description: '获取事件详细信息',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                params: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', format: 'uuid' }
                    },
                    required: ['id']
                },
                response: {
                    200: GetEventResponseSchema
                }
            },
            preHandler: [server.authenticate]
        },
        async (request, reply) => {
            const { id } = request.params as { id: string }

            const result = await getEventDetail(id)

            if (!result.success) {
                throw new Error(result.message || '获取事件详情失败')
            }

            // 转换 Date 为 ISO string
            const transformedData = {
                ...result.data!,
                startAt: result.data!.startAt.toISOString(),
                endAt: result.data!.endAt.toISOString(),
                settings: result.data!.settings as any
            }

            return reply.send({
                success: true,
                data: transformedData as any
            })
        }
    )

    /**
     * 更新事件
     * PUT /api/events/:id
     */
    server.put(
        '/api/events/:id',
        {
            schema: {
                description: '更新事件信息',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                params: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', format: 'uuid' }
                    },
                    required: ['id']
                },
                body: UpdateEventSchema,
                response: {
                    200: UpdateEventResponseSchema
                }
            },
            preHandler: [server.authenticate, server.requireAdmin]
        },
        async (request, reply) => {
            const { id } = request.params as { id: string }
            const body = request.body
            const updaterId = request.user!.userId

            // 转换 DTO
            const dto: UpdateEventDTO = {
                title: body.title,
                description: body.description,
                startAt: body.startAt ? new Date(body.startAt) : undefined,
                endAt: body.endAt ? new Date(body.endAt) : undefined,
                settings: body.settings as any
            }

            const result = await updateEvent(id, dto, updaterId)

            if (!result.success) {
                throw new Error(result.message || '更新事件失败')
            }

            // 转换 Date 为 ISO string
            const transformedData = {
                ...result.data!,
                startAt: result.data!.startAt.toISOString(),
                endAt: result.data!.endAt.toISOString(),
                settings: result.data!.settings as any
            }

            return reply.send({
                success: true,
                data: transformedData as any
            })
        }
    )

    /**
     * 删除事件
     * DELETE /api/events/:id
     */
    server.delete(
        '/api/events/:id',
        {
            schema: {
                description: '删除事件（软删除）',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                params: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', format: 'uuid' }
                    },
                    required: ['id']
                },
                response: {
                    200: DeleteEventResponseSchema
                }
            },
            preHandler: [server.authenticate, server.requireAdmin]
        },
        async (request, reply) => {
            const { id } = request.params as { id: string }
            const deleterId = request.user!.userId

            const result = await deleteEvent(id, deleterId)

            if (!result.success) {
                throw new Error(result.message || '删除事件失败')
            }

            return reply.send({
                success: true,
                data: {
                    deleted: result.data!
                }
            })
        }
    )

    /**
     * 获取事件列表
     * GET /api/events
     */
    server.get(
        '/api/events',
        {
            schema: {
                description: '获取事件列表（支持分页和筛选）',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                querystring: EventListQuerySchema,
                response: {
                    200: EventListResponseSchema
                }
            },
            preHandler: [server.authenticate]
        },
        async (request, reply) => {
            const query = request.query as any

            // TODO: 实现事件列表查询逻辑
            // 目前 event.service.ts 中没有列表查询函数，需要调用 repo 层
            // 暂时返回空列表
            return reply.send({
                success: true,
                data: {
                    data: [],
                    total: 0,
                    offset: query.offset || 0,
                    limit: query.limit || 20,
                    hasMore: false
                }
            })
        }
    )

    /**
     * 克隆事件
     * POST /api/events/:id/clone
     */
    server.post(
        '/api/events/:id/clone',
        {
            schema: {
                description: '克隆事件（创建副本）',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                params: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', format: 'uuid' }
                    },
                    required: ['id']
                },
                body: CloneEventSchema,
                response: {
                    201: CloneEventResponseSchema
                }
            },
            preHandler: [server.authenticate, server.requireAdmin]
        },
        async (request, reply) => {
            const { id } = request.params as { id: string }
            const body = request.body
            const creatorId = request.user!.userId

            // TODO: 实现事件克隆逻辑
            // 1. 获取原事件详情
            const originalEvent = await getEventDetail(id)
            if (!originalEvent.success) {
                throw new Error(originalEvent.message || '获取原事件失败')
            }

            // 2. 创建新事件
            const cloneDto: CreateEventDTO = {
                organizationId: originalEvent.data!.id, // 临时使用，实际需要从原事件获取
                title: body.newTitle || `${originalEvent.data!.title} (副本)`,
                description: originalEvent.data!.description,
                startAt: new Date(body.newStartAt!),
                endAt: new Date(body.newEndAt!),
                settings: body.cloneSettings !== false ? originalEvent.data!.settings : undefined
            }

            const result = await createEvent(cloneDto, creatorId)

            if (!result.success) {
                throw new Error(result.message || '克隆事件失败')
            }

            // 3. 如果需要克隆参与者，这里需要额外处理
            // TODO: 实现参与者克隆逻辑

            // 转换 Date 为 ISO string
            const transformedData = {
                ...result.data!,
                startAt: result.data!.startAt.toISOString(),
                endAt: result.data!.endAt.toISOString(),
                settings: result.data!.settings as any
            }

            return reply.status(201).send({
                success: true,
                data: transformedData as any
            })
        }
    )

    /**
     * 初始化事件实例
     * POST /api/events/:id/initialize
     */
    server.post(
        '/api/events/:id/initialize',
        {
            schema: {
                description: '为重复事件生成实例',
                tags: ['事件'],
                security: [{ bearerAuth: [] }],
                params: {
                    type: 'object',
                    properties: {
                        id: { type: 'string', format: 'uuid' }
                    },
                    required: ['id']
                },
                body: InitializeEventInstancesSchema,
                response: {
                    200: InitializeEventInstancesResponseSchema
                }
            },
            preHandler: [server.authenticate, server.requireAdmin]
        },
        async (request, reply) => {
            const { id } = request.params as { id: string }

            // TODO: 这个函数实际需要 participantIds 和 participantType 参数
            // 暂时使用空数组和 'member' 类型
            // 实际使用时应该从事件关联的群组或成员中获取
            const result = await initializeEventInstances(id, [], 'member')

            if (!result.success) {
                throw new Error(result.message || '初始化事件实例失败')
            }

            // 转换响应数据
            const data = result.data as any
            const transformedData = {
                eventId: data.eventId || id,
                instanceCount: data.instanceCount || 0,
                firstInstanceDate: data.firstInstanceDate?.toISOString(),
                lastInstanceDate: data.lastInstanceDate?.toISOString()
            }

            return reply.send({
                success: true,
                data: transformedData
            })
        }
    )
}

export default eventRoutes

// fastify-autoload will use this exported 'prefix' when mounting the plugin
export const prefix = '/api/events'
